package com.iedu.demo.lgq.service.impl;

import com.iedu.demo.lgq.entity.TbOrderReview;
import com.iedu.demo.lgq.entity.TbReviewMedia;
import com.iedu.demo.lgq.mapper.ReviewMapper;
import com.iedu.demo.lgq.service.OrderReviewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class OrderReviewServiceImpl implements OrderReviewService {

    @Autowired
    private ReviewMapper reviewMapper;

    @Override
    public TbOrderReview addReview(TbOrderReview review, List<TbReviewMedia> mediaList) {
        review.setCreatedAt(LocalDateTime.now()); // 设置当前时间
        reviewMapper.insertReview(review);

        if (mediaList != null && !mediaList.isEmpty()) {
            for (TbReviewMedia media : mediaList) {
                media.setCommentId(review.getId()); // 设置关联的评价 ID
                reviewMapper.insertReviewMedia(media);
            }
        }

        return review;
    }

    @Override
    public List<TbOrderReview> getReviewsByItemId(Integer itemId) { // 将 productId 改为 itemId
        List<TbOrderReview> reviews = reviewMapper.findByItemId(itemId); // 将 findByProductId 改为 findByItemId
        for (TbOrderReview review : reviews) {
            review.setMedia(reviewMapper.findMediaByCommentId(review.getId())); // 设置媒体文件列表
        }
        return reviews;
    }

    @Override
    public List<TbOrderReview> getReviewsByUserId(Integer userId) {
        List<TbOrderReview> reviews = reviewMapper.findByUserId(userId);
        for (TbOrderReview review : reviews) {
            review.setMedia(reviewMapper.findMediaByCommentId(review.getId())); // 设置媒体文件列表
        }
        return reviews;
    }

    @Override
    public TbOrderReview getReviewById(Integer reviewId) {
        TbOrderReview review = reviewMapper.findByReviewId(reviewId);
        if (review != null) {
            review.setMedia(reviewMapper.findMediaByCommentId(reviewId)); // 设置媒体文件列表
        }
        return review;
    }

    @Override
    public TbOrderReview updateReview(TbOrderReview review) {
        reviewMapper.updateReview(review);
        return review;
    }

    @Override
    public void deleteReview(Integer reviewId) {
        reviewMapper.deleteReviewMedia(reviewId); // 先删除媒体文件
        reviewMapper.deleteReview(reviewId); // 再删除评价
    }
}
